using B.S.XZYData.Api.Wrter.Application.Command.AssemblyWorkOrder;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.AssemblyWorkOrder
{
    /// <summary>
    /// 批量打印装配工单处理器
    /// </summary>
    public class BatchPrintAssemblyWorkOrderHandler : IRequestHandler<BatchPrintAssemblyWorkOrderCommand, ApiResult<List<PrintAssemblyWorkOrderResponseDto>>>
    {
        private readonly IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> _assemblyWorkOrderRepo;
        private readonly IBaseRepository<AssemblyWorkOrderProductDetail> _productDetailRepo;
        private readonly ILogger<BatchPrintAssemblyWorkOrderHandler> _logger;

        public BatchPrintAssemblyWorkOrderHandler(
            IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> assemblyWorkOrderRepo,
            IBaseRepository<AssemblyWorkOrderProductDetail> productDetailRepo,
            ILogger<BatchPrintAssemblyWorkOrderHandler> logger)
        {
            _assemblyWorkOrderRepo = assemblyWorkOrderRepo;
            _productDetailRepo = productDetailRepo;
            _logger = logger;
        }

        public async Task<ApiResult<List<PrintAssemblyWorkOrderResponseDto>>> Handle(BatchPrintAssemblyWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<List<PrintAssemblyWorkOrderResponseDto>>();
            try
            {
                if (request.Ids == null || !request.Ids.Any())
                {
                    res.Msg = "工单ID列表不能为空";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                var printResponses = new List<PrintAssemblyWorkOrderResponseDto>();

                foreach (var id in request.Ids)
                {
                    try
                    {
                        // 查询装配工单
                        var workOrder = await _assemblyWorkOrderRepo.GetValue(id);
                        if (workOrder == null)
                        {
                            _logger.LogWarning($"装配工单ID {id} 不存在，跳过打印");
                            continue;
                        }

                        // 查询关联的产品明细
                        var productDetails = _productDetailRepo.GetAll()
                            .Where(x => !x.IsDeleted && x.WorkOrderId == id)
                            .OrderBy(x => x.HierarchyNumber)
                            .ToList();

                        // 构建打印响应数据
                        var printResponse = new PrintAssemblyWorkOrderResponseDto
                        {
                            WorkOrder = new AssemblyWorkOrderPrintInfoDto
                            {
                                Id = workOrder.Id,
                                DocumentNumber = workOrder.DocumentNumber,
                                WorkOrderCount = workOrder.WorkOrderCount,
                                CompletedWorkOrderCount = workOrder.CompletedWorkOrderCount,
                                DocumentProgress = workOrder.DocumentProgress,
                                Remarks = workOrder.Remarks,
                                Creator = workOrder.Creator,
                                CreatorDate = workOrder.CreatorDate,
                                Updator = workOrder.Updator,
                                UpdatorDate = workOrder.UpdatorDate
                            },
                            ProductDetails = productDetails.Select(detail => new ProductDetailPrintInfoDto
                            {
                                Id = detail.Id,
                                HierarchyNumber = detail.HierarchyNumber,
                                ProductNumber = detail.ProductNumber,
                                ProductName = detail.ProductName,
                                ProductSpecification = detail.ProductSpecification,
                                WorkOrderDetailNumber = detail.WorkOrderDetailNumber,
                                Quantity = detail.Quantity,
                                CompletedQuantity = detail.CompletedQuantity,
                            }).ToList()
                        };

                        printResponses.Add(printResponse);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"处理装配工单ID {id} 打印数据时发生异常：{ex.Message}");
                        // 继续处理其他工单，不中断整个批量操作
                    }
                }

                if (!printResponses.Any())
                {
                    res.Msg = "没有找到有效的装配工单数据";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                res.Data = printResponses;
                res.Code = ApiEnum.Success;
                res.Msg = $"批量获取打印数据成功，共 {printResponses.Count} 个工单";

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"批量获取装配工单打印数据异常：{ex.Message}");
                res.Msg = "批量获取装配工单打印数据异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 